import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class ApiService {

  async request(method, url, data = {}) {
    const headers = {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${localStorage.getItem('token')}`,
    };
    const trim = s => s === undefined || s === null ? '' : s;
    const args: any = [[
      // isDevMode() ? '/api' : '//yanduapi.t.oc1.xyz/v2',
      window['baseUrl'],
      url.replace(/:([^&;/?]+)/g, (...s) => trim(data[s[1]])),
    ].join('/')];

    const params = Object.keys(data).reduce((obj, key) => {
      obj[key] = trim(data[key]);
      return obj;
    }, {});
    const response = {
      observe: "response" as 'body', // to display the full response
      responseType: "json"
    }
    if (method === 'get' || method === 'delete') {
      args.push({ headers, params, response });
    } else {
      args.push(params, { headers });
    }

    try {
      // const requestData_old = JSON.parse(localStorage.getItem('requestData'));
      const requestData = {
        url: args[0],
        method: method,
        // timestamp: (new Date()).getTime(),
      }
      console.log(args)

      return await this.http[method](...args).subscribe(resp => {
        // Here, resp is of type HttpResponse<MyJsonData>.
        // You can inspect its headers:
        console.log(resp);
        // And access the body directly, which is typed as MyJsonData as requested.
        // console.log(resp.body.someField);
      });

      // }
    } catch (e) {
      console.log(e)
      const { status, statusText } = e;
      if (status != 401) {
        // this.notify.create('error', `${status}`, e.error.message);
      }
      if (status === 401) {
        localStorage.clear();
        window.location.assign('/login')
        // this.router.navigate(['/login']);
      }
      throw e;
    }
  }


  delete = (url) => (data?) => this.request('delete', url, data);
  get = (url) => (data?) => this.request('get', url, data)
  patch = (url) => (data?) => this.request('patch', url, data);
  post = (url) => (data?) => this.request('post', url, data);
  put = (url) => (data?) => this.request('put', url, data);



  constructor(
    private http: HttpClient
  ) { }
}